﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;
using SapaFinance.GenericRepository;

namespace SapaFinance.Services
{
    public interface IAgentService
    {
        IEnumerable<AgentDTO> GetListDTO();
        IEnumerable<SelectListItem> GetSelectedListById(Guid id);
        void Insert(AgentDTO dto);
        void Delete(Guid id);
        void Update(AgentDTO dto);
        Agent GetAgent(Guid id);
    }

    public class AgentService : IAgentService
    {
        private readonly IGenericRepository<Agent, Guid> _agentRepository;
        private readonly IMappingEngine _mappingEngine;
        private readonly IEntityFactory _entityFactory;
        private readonly IUnitOfWork _unitOfWork;

        public AgentService(IGenericRepository<Agent, Guid> agentRepository, IUnitOfWork unitOfWork, IMappingEngine mappingEngine, IEntityFactory entityFactory)
        {
            _agentRepository = agentRepository;
            _unitOfWork = unitOfWork;
            _mappingEngine = mappingEngine;
            _entityFactory = entityFactory;
        }

        #region IAgentService Members


        public IEnumerable<SelectListItem> GetSelectedListById(Guid id)
        {
            var result = new List<SelectListItem> { _entityFactory.BuildEmptyItem() };
            var agents = _agentRepository.GetAll();
            result.AddRange(_mappingEngine.Map<IEnumerable<Agent>, IEnumerable<SelectListItem>>(agents));
            foreach (var item in result.Where(item => item.Value.Equals(id.ToString())))
            {
                item.Selected = true;
            }
            return result;
        }

        public IEnumerable<AgentDTO> GetListDTO()
        {
            return _mappingEngine.Map<IEnumerable<Agent>, IEnumerable<AgentDTO>>(_agentRepository.GetAll());
        }
        public virtual void Insert(AgentDTO dto)
        {
            var entity = _entityFactory.BuildAgent(dto);
            _agentRepository.Insert(entity);
            _unitOfWork.Flush();
        }

        public virtual void Delete(Guid id)
        {
            var agent = _agentRepository.GetById(id);
            _agentRepository.Delete(agent);
            _unitOfWork.Flush();
        }

        public virtual void Update(AgentDTO dto)
        {
            var agent = _agentRepository.GetById(dto.UID);
            agent.Name = dto.Name;
            agent.IsSelfAgent=dto.IsSelfAgent;
            _agentRepository.Update(agent);
            _unitOfWork.Flush();
        }

        public Agent GetAgent(Guid id)
        {
            return _agentRepository.GetById(id);
        }

        #endregion
    }
}